package fr.univ.lille1.android;

import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.ViewById;
import com.googlecode.androidannotations.annotations.res.HtmlRes;
import com.googlecode.androidannotations.annotations.res.StringRes;

import fr.univ.lille1.android.auth.AuthenticationService;

@EActivity(R.layout.activity_signin)
public class SignInActivity extends BaseActivity {
	// Gui.
	@ViewById(R.id.textViewWelcome)
	TextView mTextViewWelcome;
	@ViewById(R.id.editTextEmail)
	EditText mEditTextEmail;
	@ViewById(R.id.editTextPassword)
	EditText mEditTextPassword;
	@ViewById(R.id.buttonTagThisSignIn)
	Button mButtonTagThisSignIn;

	// Resources.
	@HtmlRes(R.string.text_welcome)
	CharSequence mTextWelcome;
	@StringRes(R.string.app_name)
	String mAppName;

	@Override
	public void onSignedIn(AuthenticationService service) {
		super.onSignedIn(service);
		CommentActivity_.intent(this).start();
		finish();
	}

	@AfterViews
	void afterView() {
		final String textWelcome = String.format(mTextWelcome.toString(),
				mAppName);
		mTextViewWelcome.setText(Html.fromHtml(textWelcome));
	}

	@Click(R.id.buttonTagThisSignIn)
	void tagThisSignInClick() {
		tryConnect();
	}

	/**
	 * Try to connect with the tag this form.
	 */
	public void tryConnect() {
		mButtonTagThisSignIn.setEnabled(false);
		mEditTextEmail.setError(null);
		mEditTextPassword.setError(null);

		boolean cancel = false;
		View focusView = null;

		final String email = mEditTextEmail.getText().toString();
		final String password = mEditTextPassword.getText().toString();

		// User must fill all fields.
		if (TextUtils.isEmpty(email)) {
			mEditTextEmail.setError(getString(R.string.error_message_no_value));
			cancel = true;
			focusView = mEditTextEmail;
		} else if (TextUtils.isEmpty(password)) {
			mEditTextPassword
					.setError(getString(R.string.error_message_no_value));
			cancel = true;
			focusView = mEditTextPassword;
		}
		// If there is one field empty, we indicate at the user. Otherwise, we
		// launch the connection request.
		if (cancel) {
			focusView.requestFocus();
			mButtonTagThisSignIn.setEnabled(true);
		} else {
			setProgressBarIndeterminateVisibility(true);
			mAuthentication.signIn(email, password);
		}
	}
}
